package com.leyou.auth.config;

import com.leyou.auth.interceptor.LoginInterceptor;
import com.leyou.pojo.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * 要想让拦截器生效，必须添加拦截器，到拦截器链中
 */
@Configuration
@ConditionalOnProperty(prefix = "ly.auth",name = "enable",havingValue = "true")
public class MvcConfig implements WebMvcConfigurer {
    //因为在spring中，所以可以直接注入
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private ClientProperties clientProperties;
    /**
     * 添加拦截器
     * @param registry  拦截器注册器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //添加拦截器
        InterceptorRegistration registration = registry.addInterceptor(new LoginInterceptor(jwtUtils));
        //设置拦截路径
        List<String> includePathPattern = clientProperties.getIncludePathPattern();
        if(!CollectionUtils.isEmpty(includePathPattern)){
            registration.addPathPatterns(includePathPattern);
        }
        List<String> excludePathPattern = clientProperties.getExcludePathPattern();
        if(!CollectionUtils.isEmpty(excludePathPattern)){
            registration.excludePathPatterns(excludePathPattern);
        }
    }
}
